package com.heima.account.action.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.account.action.IAccountAction;
import com.heima.account.entity.Account;
import com.heima.account.entity.AccountFreeze;
import com.heima.account.service.IAccountFreezeService;
import com.heima.account.service.IAccountService;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AccountActionImpl implements IAccountAction {

    @Autowired
    private IAccountFreezeService accountFreezeService;
    @Autowired
    private IAccountService accountService;


    @Override
    public void prepare(Integer userId, Integer money) { //money代表的是需要扣减的金额
//        - 记录冻结金额和事务状态到account_freeze表
//        AccountFreeze accountFreeze = new AccountFreeze();
//        String xid = RootContext.getXID(); //全局的事务id
//        accountFreeze.setXid(xid);
//        accountFreeze.setUserId(userId);
//        accountFreeze.setFreezeMoney(money);
//        accountFreezeService.save(accountFreeze);
//  - 扣减account表可用金额  update tb_account set money=money-? where user_id=？


        LambdaUpdateWrapper<Account> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.setSql("money=money-"+money);
        updateWrapper.eq(Account::getUserId,userId);
        accountService.update(updateWrapper);

    }

    @Override
    public boolean commit(BusinessActionContext context) {
//        - 根据xid删除account_freeze表的冻结记录  delete from  account_freeze where xid=??
        LambdaQueryWrapper<AccountFreeze> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AccountFreeze::getXid,context.getXid());
        accountFreezeService.remove(queryWrapper);

        return true;
    }

    @Override
    public boolean rollback(BusinessActionContext context) {
//        - 修改account表，恢复可用金额     update tb_account set money=money+? where user_id=？
        LambdaUpdateWrapper<Account> updateWrapper = new LambdaUpdateWrapper<>();

        Integer userId = (Integer) context.getActionContext("userId");
        Integer money = (Integer) context.getActionContext("money");

        updateWrapper.setSql("money=money+"+money);
        updateWrapper.eq(Account::getUserId,userId);
        accountService.update(updateWrapper);

//        - 删除冻结记录

//        - 根据xid删除account_freeze表的冻结记录  delete from  account_freeze where xid=??
        LambdaQueryWrapper<AccountFreeze> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AccountFreeze::getXid,context.getXid());
        accountFreezeService.remove(queryWrapper);
        return true;
    }
}
